package com.itheima.day2.hiorder;

import java.util.Collection;
import java.util.List;
import java.util.function.BinaryOperator;

public class C04SimpleStream02<T> {

    private Collection<T> collection;

    private C04SimpleStream02(Collection<T> collection) {
        this.collection = collection;
    }

    public static <T> C04SimpleStream02<T> of(Collection<T> collection) {
        return new C04SimpleStream02<>(collection);
    }

    // o 代表 p 的初始值
    public T reduce(T o, BinaryOperator<T> operator) {
        T p = o; // 上次的合并结果
        for (T t : collection) { // t 是本次遍历的元素
            p = operator.apply(p, t);
        }
        return p;
    }

    public static void main(String[] args) {
        List<Integer> list = List.of(1, 2, 3, 4, 5);

        System.out.println(C04SimpleStream02.of(list).reduce(0, Integer::sum));
        System.out.println(C04SimpleStream02.of(list).reduce(Integer.MAX_VALUE, Math::min));
        System.out.println(C04SimpleStream02.of(list).reduce(Integer.MIN_VALUE, Math::max));
    }

}
